﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using MPCR.Client.Custom;
using System.Windows.Media.Animation;
using MPCR.Contracts.Custom;
using MPCR.Contracts.Entity;
using MPCR.Client.Pages.Business;
using System.Windows.Threading;
using MPCR.Client.Dialog;
using MPCR.Contracts.PrinterSetting;
using MPCR.Client.View.Dialog;
using MPCR.Client.TouchView.Home;

namespace MPCR.Client.TouchView
{
    /// <summary>
    /// TouchMainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class TouchMainWindow : Window
    {

        private PageBusinessTouchPanel touchPanel = null;
        public TouchMainWindow()
        {
            InitializeComponent();
            //初始化窗体变量设置
            
            List<DictionaryClass> configList = App.MPCRClient.GetAllDictionary();
            UpdateHotelTitle();
            this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
            ApplicationSetting.Init();
            ApplicationSetting.NoticeClientToUpdateEvent += new EventHandler(UpdateClientData);
            ApplicationSetting.NoticeClientToExitEvent += new EventHandler(NoticeClientToExit);
            //打印状态
            ApplicationSetting.RefreshPrintErrEvent += new EventHandler(ReferencePrintErrInfo);

            ApplicationSetting.UpdateHotelTitleEvent += new EventHandler(ApplicationSetting_UpdateHotelTitleEvent);
            ApplicationSetting.LoginRemoteServer();
            ApplicationSetting.CheckUpdateStatus();
            //为后台线程添加委托
            ApplicationSetting.UpdateStatusBarMemberCardConnectionStatusEvent += new EventHandler(ApplicationSetting_UpdateStatusBarMemberCardConnectionStatusEvent);
            this.Closing += new System.ComponentModel.CancelEventHandler(MainWindow_Closing);
        }

        public TouchMainWindow(bool hasTable):this()
        {
            if (hasTable)
            {
                mainFrame.Content = null;
            }
            else
            {
                mainFrame.Content = new MPCR.Client.TouchView.Home.PageBusinessTouchPanel();
            }
        }

        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            ApplicationSetting.UpdateStatusBarBillAccountInfo(sender, e);
            ApplicationSetting.RefreshFoodChangeInfo(sender, e);
            //打印状态
            ApplicationSetting.RefreshPrintErrChangeInfo(sender, e);
            //显示时间线程
            this.ShowTimeNow();
        }

        #region 检查服务器并设置状态

        //改变集团服务器连接状态按钮提示文字的委托
        private delegate void delegateRefreshServerConnectionButton();
        private void RefreshServerConnectionButton()
        {
            RadialGradientBrush brush = new RadialGradientBrush();
            brush.Center = new Point(0.5, 0.5);
            brush.RadiusX = 0.5;
            brush.RadiusY = 0.5;
            if (MPCR.Client.Util.ApplicationSetting.IsRemoteLogin)
            {
                this.ConnectText.Content = "云端已连接";
                GradientStopCollection gradient = new GradientStopCollection();
                gradient.Add(new GradientStop(Colors.FloralWhite, 0));
                gradient.Add(new GradientStop(Colors.Green, 1));
                brush.GradientStops = gradient;
                this.ConnectState.Fill = brush;
            }
            else
            {
                this.ConnectText.Content = "云端未连接";
                GradientStopCollection gradient = new GradientStopCollection();
                gradient.Add(new GradientStop(Colors.FloralWhite, 0));
                gradient.Add(new GradientStop(Colors.Red, 1));
                brush.GradientStops = gradient;
                this.ConnectState.Fill = brush;
            }
        }

        //返回UI线程改变按钮文字
        void ApplicationSetting_UpdateStatusBarMemberCardConnectionStatusEvent(object sender, EventArgs e)
        {
            Dispatcher.BeginInvoke(new delegateRefreshServerConnectionButton(this.RefreshServerConnectionButton));
        }

        //重新连接集团服务器
        private void btnRefreshServerConnection_Click(object sender, RoutedEventArgs e)
        {
            ApplicationSetting.LoginRemoteServer();
        }

        #endregion

        private void mainFrame_ContentRendered(object sender, EventArgs e)
        {
            Page p = (this.mainFrame.Content as Page);
            p.Focusable = true;
            p.Focus();
        }

        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            base.OnClosing(e);

            // 注释原因：下面代码当用户在“确认退出系统？”点取消按钮导致不继续打印。
            // PrintHelper.GetSingleton().IsShouldQuit = true;
        }

        //菜单按钮事件
        private void ToolMeunBarButton_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        //门店按钮
        private void btnShowHotel_Click(object sender, RoutedEventArgs e)
        {

        }
        //用户按钮
        private void btnChangePwd_Click(object sender, RoutedEventArgs e)
        {

        }

        /*
        * 2012-08-31重构代码
        * 钱钦
        * 检测到其他客户端更新时关闭本客户端，防止出现营业数据错乱
        */
        private delegate void delegateNoticeNoticeClientToExit();
        private void NoticeClientToExit(object sender, EventArgs e)
        {
            Dispatcher.BeginInvoke(new delegateNoticeNoticeClientToExit(DoNoticeClientToExit));
        }

        public void DoNoticeClientToExit()
        {
            DialogAlert dialog = new DialogAlert("门店数据已开始更新，为防止数据出现异常，客户端将立即退出！");
            dialog.Owner = this;
            dialog.ShowDialog();
            System.Environment.Exit(0);

            //备注，以后改成等待对话框，并提供刷新
        }

        void ApplicationSetting_UpdateHotelTitleEvent(object sender, EventArgs e)
        {
            Dispatcher.BeginInvoke(new delegateRefreshServerConnectionButton(this.UpdateHotelTitle));
        }

        private void UpdateHotelTitle()
        {
            string hotelName = ApplicationSetting.HotelInfo == null ? "未命名门店" : ApplicationSetting.HotelInfo.Title;
            HotelInfoBtn.Text = hotelName;
            runLoginBtn.Text = "当前用户: [" + ApplicationSetting.Employee.Title + "],工号: [" + ApplicationSetting.Employee.Number + "]";
        }

        //////打印状态//////
        void ReferencePrintErrInfo(object sender, EventArgs e)
        {
            Dispatcher.BeginInvoke(new delegateRefreshServerConnectionButton(RefreshStatusPrintErrInfo));
        }
        private void RefreshStatusPrintErrInfo()
        {
            string myStep = string.Empty;
            DateTime from = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd") + " 00:00:00");
            DateTime to = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd") + " 23:59:59");

            myStep = "构造状态列表。";
            var status = new List<int>();
            status.Add(PrintTaskStatus.ERROR);
            status.Add(PrintTaskStatus.PRINTER_STATUS_ERROR);
            //List<PrinterLog> logList = App.MPCRClient.GetPrinterLogList(0,null,null,null,null,from,to);
            try
            {
                myStep = "从数据获打印取记录列表。";
                List<PrinterLog> logList = App.MPCRClient.GetPrinterLogListByStatus(status, from, to);
                //int count = logList.Count(n => n.Status == PrintTaskStatus.ERROR || n.Status==PrintTaskStatus.PRINTER_STATUS_ERROR);
                if (logList != null)
                {
                    myStep = "打印取记录列表不为空。";
                    int count = logList.Count;
                    if (count > 0)
                    {
                        myStep = "获取主窗口PageBusinessHall。";
                        touchPanel = mainFrame.Content as PageBusinessTouchPanel;
                        if (touchPanel == null) return;

                        // 源代码，修改提示方式,Mark By Tom20121127
                        //getHallPage.runPrintErrLog.Text = string.Format("单子打印失败数:  \t{0}个", count);
                        //getHallPage.textPrintErrLog.Visibility = Visibility.Visible;

                        // 修改提示方式,Add By Tom20121127
                        if (DialogHandlePrintErrorCreator.DialogHandlePrintError == null)
                        {
                            try
                            {
                                log4net.LogManager.GetLogger(
                                    System.Configuration.ConfigurationManager.AppSettings["LOGGER_NAME"])
                                       .Info("统计打印错误弹框不存在。");
                            }
                            catch
                            { }

                            myStep = "创建弹出打印错误处理对话框。";
                            DialogHandlePrintErrorCreator.DialogHandlePrintError =
                                DialogHandlePrintErrorCreator.CreateDialogHandlePrintError();
                            DialogHandlePrintErrorCreator.DialogHandlePrintError.Tag = logList;
                            DialogHandlePrintErrorCreator.DialogHandlePrintError.Owner = this;

                            myStep = "存储当前的活动窗口，便于激活。";
                            Window topWin = DialogHelper.GetTopWindow();

                            myStep = "显示弹出窗口。";
                            DialogHandlePrintErrorCreator.DialogHandlePrintError.Show();
                            myStep = "设置窗口Z顺序。";
                            DialogHelper.SetWindowZOrder(DialogHandlePrintErrorCreator.DialogHandlePrintError);
                            DialogHandlePrintErrorCreator.DialogHandlePrintError.ShowActivated = false;

                            myStep = "激活当前活动窗口。";
                            topWin.Activate();
                        }
                        else
                        {
                            try
                            {
                                log4net.LogManager.GetLogger(
                                    System.Configuration.ConfigurationManager.AppSettings["LOGGER_NAME"])
                                       .Info("统计打印错误弹框存在。");
                            }
                            catch
                            { }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // 忽略：不为活动窗口时，获取不到顶层窗口。
                try
                {
                    myStep = "销毁打印错误弹框。";
                    DialogHandlePrintErrorCreator.SetDialogHandlePrintError();
                }
                catch
                {
                }
            }

        }

        void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            DialogExit windowExit = new DialogExit();
            windowExit.Owner = this;
            bool? result = windowExit.ShowDialog();
            if (result == true)
            {
                Environment.Exit(0);
            }
            else
            {
                e.Cancel = true;
                //SetFocusToHallPage();
                return;
            }
        }

        private void ShowTimeNow()
        {
            tm = new DispatcherTimer();         //延迟2秒关闭窗口
            tm.Tick += new EventHandler(tm_Tick);
            tm.Interval = TimeSpan.FromSeconds(1);
            tm.Start();
        }

        //计时程序
        DispatcherTimer tm = null;
        int k = 0;
        private void tm_Tick(object sender, EventArgs e)
        {
            k++;
            if (k >= 1)
            {
                this.textTimeNow.Text = DateTime.Now.ToString();
                k = 0;
            }
        }


        public void UpdateClientData(object sender, EventArgs e)
        {
            // WSS Add By Tom20120919
            int msgCode = -10;
            // end

            int dpmtID = ApplicationSetting.DepartmentId;          //门店ID，从本地配置文件中获得

            versionToUpdate.Clear();            //检查更新前清除上次的检查结果

            //List<MPCR.Client.GroupService.VersionControl> listVersion = App.GroupService.GetVersion(dpmtID);            //从集团服务器获取本地门店对应的更新版本信息
            // WSS Add By Tom20120919
            IList<MPCR.Client.GroupWebService.SyncVersionControl> listVersion = App.GroupWebService.GetVersion(Util.Utils.GetTokenNew(),
                dpmtID,
                out msgCode);
            // end

            if (listVersion == null)
            {
                //MessageBox.Show("门店注册信息异常！");
                // WSS Add By Tom20120919
                var msg = string.Empty;
                var wsMsg = Util.Utils.WebServiceAlertMessage(msgCode);
                if (!string.IsNullOrWhiteSpace(wsMsg))
                    msg = wsMsg;
                else msg = "门店注册信息异常！";
                MessageBox.Show(msg);
                // end

                return;
            }
            else if (listVersion.Count > 0)
            {
                //MessageBox.Show("Need to update!");
                foreach (MPCR.Client.GroupWebService.SyncVersionControl v in listVersion)          //遍历获取到的版本号列表，检查相应需要更新的数据
                {
                    VersionControl getVersion = App.MPCRClient.GetVersion(v.VersionType);
                    if (getVersion == null)            //本地未查询到相关版本号则认为是第一次更新，将版本号信息存储到本地
                    {
                        VersionControl version = new VersionControl();
                        version.DpmtId = v.BranchId;
                        version.VersionType = v.VersionType;
                        version.VersionNumber = 0;          //默认版本号为零，等第一次更新成功后会与集团版本号一致
                        version.Memo = v.Memo;
                        if (!App.MPCRClient.SaveVersion(version))
                        {
                            continue;
                        }
                    }
                    else
                    {
                        if (v.VersionNumber == getVersion.VersionNumber)           //比较版本号，如果不一致则需要更新门店的相关信息
                        {
                            continue;
                        }
                    }
                    //此处针对类型进行判断，并执行更新操作
                    this.versionDpmtID = dpmtID;
                    //this.versionNumber = Convert.ToInt32(v.VersionNumber);
                    //this.versionType = v.VersionType;
                    this.versionToUpdate.Add(v.VersionType, Convert.ToInt32(v.VersionNumber));
                }
                if (this.versionToUpdate.Keys.Count > 0)
                {
                    Dispatcher.BeginInvoke(new delegateDoUpdate(AskForUpdate));         //回到主线程执行相关操作
                }
                else
                {
                    Dispatcher.BeginInvoke(new delegateNoticeNoUpdateToCommit(NoticeNoUpdateToCommit));
                }
            }
            else
            {
                Dispatcher.BeginInvoke(new delegateNoticeNoUpdateToCommit(NoticeNoUpdateToCommit));
            }
        }
        private int versionDpmtID;
        private Dictionary<string, int> versionToUpdate = new Dictionary<string, int>();

        private delegate void delegateNoticeNoUpdateToCommit();
        private void NoticeNoUpdateToCommit()
        {
            this.MessageTrigger2 = new ControlHint.DelegateMessageTrigger(this.OnMessageTrigger2);        //渐变窗口弹出提示
            this.MessageTrigger2("当前门店数据为最新版本！");
        }

        private delegate void delegateDoUpdate();
        private void DoUpdate()
        {
            MessageBox.Show("OK");
        }

        private void AskForUpdate()
        {
            //检查是否有其他客户端同时在更新
            MutexVariable mutexUpdate = App.MPCRClient.GetMutex(MutexType.MUTEX_TYPE_UPDATE);
            if (mutexUpdate == null)
            {
                //App.MPCRClient.SetMutex(MutexType.MUTEX_TYPE_UPDATE, true);
                ApplicationSetting.isSelfUpdating = true;
            }
            else
            {
                if (mutexUpdate.MutexValue == true && ApplicationSetting.isSelfUpdating == false)
                {
                    //DoNoticeClientToExit();            //通知更新进度对话框，更新中止
                    return;
                }
            }

            DialogRequestUpdate dialog = new DialogRequestUpdate();         //询问是否更新的窗口
            dialog.Owner = this;
            bool? result = dialog.ShowDialog();
            if (result == true)
            {
                //打开更新模态窗口，显示更新进度
                //bool willBackup = Convert.ToBoolean(dialog.chkBackup.IsChecked);
                //ApplicationSetting.willBackup = willBackup;
                DialogUpdateProgress updateDialog = new DialogUpdateProgress(this.versionDpmtID, this.versionToUpdate);
                updateDialog.Owner = this;
                result = updateDialog.ShowDialog();
                if (result == true)
                {
                    //更新完成后对本地客户端的相关数据及界面进行刷新操作（桌台、客位）

                }
            }
            else
            {

            }
        }

        private ControlHint.DelegateMessageTrigger MessageTrigger2 = null;       //渐变弹出框的触发器
        private void OnMessageTrigger2(string message)       //显示透明渐变提示
        {
            this.HintCenter.Title = message;
            Storyboard story = this.FindResource("story4Hint") as Storyboard;
            if (story != null) story.Begin();
        }

        private void Grid_MouseDown(object sender, MouseButtonEventArgs e)
        {
            touchPanel = mainFrame.Content as PageBusinessTouchPanel;

            //if (this.ToolMeunBarButton.IsChecked == true)
            //{
            //    this.ToolMeunBarButton.IsChecked = false;
            //}
        }
    }
}
